package com.ktgj.flight.common.pay.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.net.www.protocol.https.Handler;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

public class CallbackUtil {

    private static final Log logger;
    public static final String DEFAULT_CHARSET = "GBK";
    public static final String HTTP_METHOD_POST = "POST";
    public static final String HTTP_METHOD_GET = "GET";
    public static int DEFAULT_TIMEOUT;
    public static final String HTTP_METHOD_DEFAULT = "GET";
    public static final String HTTP_PREFIX = "http://";
    public static final String HTTPS_PREFIX = "https://";

    static {
        System.setProperty("sun.net.inetaddr.ttl", "3600");
        logger = LogFactory.getLog(CallbackUtil.class);
        DEFAULT_TIMEOUT = 60000;
    }

    public CallbackUtil() {
    }

    public static String httpRequest(String targetUrl, String queryString, String method, String charSet) throws Exception {
        {
            HttpURLConnection urlConn = null;
            URL destURL = null;
            boolean httpsFlag = false;
            if (targetUrl != null && targetUrl.trim().length() != 0) {
                targetUrl = targetUrl.trim();
                if (targetUrl.toLowerCase().startsWith("https://")) {
                    httpsFlag = true;
                } else if (!targetUrl.toLowerCase().startsWith("http://")) {
                    targetUrl = "http://" + targetUrl;
                }

                if (queryString != null) {
                    queryString = queryString.trim();
                }

                if (method == null || !method.equals("POST") && !method.equals("GET")) {
                    throw new IllegalArgumentException("invalid http method : " + method);
                } else {
                    String baseUrl = "";
                    String params = "";
                    String fullUrl = "";
                    int index = targetUrl.indexOf("?");
                    if (index != -1) {
                        baseUrl = targetUrl.substring(0, index);
                        params = targetUrl.substring(index + 1);
                    } else {
                        baseUrl = targetUrl;
                    }

                    if (queryString != null && queryString.trim().length() != 0) {
                        if (params.trim().length() > 0) {
                            params = params + "&" + queryString;
                        } else {
                            params = params + queryString;
                        }
                    }

                    fullUrl = baseUrl + (params.trim().length() == 0 ? "" : "?" + params);
                    StringBuffer result = new StringBuffer(2000);

                    try {
                        if (method.equals("POST")) {
                            destURL = new URL(baseUrl);
                            logger.info("POST方式，url：" + baseUrl);
                        } else {
                            destURL = new URL((URL) null, fullUrl, new Handler());
                            logger.info("GET方式，url：" + fullUrl);
                        }

                        if (httpsFlag) {
                            trustAllHttpsCertificates();
                            urlConn = (HttpsURLConnection) destURL.openConnection();
                        } else {
                            urlConn = (HttpURLConnection) destURL.openConnection();
                        }

                        ((HttpURLConnection) urlConn).setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet);
                        ((HttpURLConnection) urlConn).setDoOutput(true);
                        ((HttpURLConnection) urlConn).setDoInput(true);
                        ((HttpURLConnection) urlConn).setAllowUserInteraction(false);
                        logger.info(method);
                        ((HttpURLConnection) urlConn).setUseCaches(false);
                        ((HttpURLConnection) urlConn).setRequestMethod(method);
                        ((HttpURLConnection) urlConn).setConnectTimeout(DEFAULT_TIMEOUT);
                        ((HttpURLConnection) urlConn).setReadTimeout(DEFAULT_TIMEOUT);
                        ((HttpURLConnection) urlConn).setRequestProperty("User-Agent", "EPOS");
                        if (method.equals("POST")) {
                            OutputStream os = ((HttpURLConnection) urlConn).getOutputStream();
                            OutputStreamWriter osw = new OutputStreamWriter(os, charSet);
                            osw.write(params);
                            osw.flush();
                            osw.close();
                        }

                        BufferedInputStream is = new BufferedInputStream(((HttpURLConnection) urlConn).getInputStream());
                        BufferedReader br = new BufferedReader(new InputStreamReader(is, charSet));
                        String temp = null;

                        while ((temp = br.readLine()) != null) {
                            result.append(temp);
                            result.append("\n");
                        }

                        int responseCode = ((HttpURLConnection) urlConn).getResponseCode();
                        logger.info("ResponseCode[" + responseCode + "]\n" + "result[" + result + "]");
                        if (responseCode == 200) {
                            String var17 = result.toString();
                            return var17;
                        }
                    } catch (Exception var20) {
                        logger.error("connection error : " + var20.getMessage(), var20);
                        throw var20;
                    } finally {
                        if (urlConn != null) {
                            ((HttpURLConnection) urlConn).disconnect();
                        }

                    }
                    return null;
                }
            } else {
                throw new IllegalArgumentException("invalid targetUrl : " + targetUrl);
            }
        }
    }

    public static Map queryString(String queryResult, String splitChar) {
        String[] keyValuePairs = queryResult.split(splitChar);
        Map<String, String> map = new HashMap();
        String[] var7 = keyValuePairs;
        int var6 = keyValuePairs.length;

        for(int var5 = 0; var5 < var6; ++var5) {
            String keyValue = var7[var5];
            if (keyValue.indexOf("=") != -1) {
                String[] args = keyValue.split("=", 2);
                if (args.length == 2) {
                    map.put(args[0], args[1]);
                }

                if (args.length == 1) {
                    map.put(args[0], "");
                }
            }
        }
        return map;
    }

    private static void trustAllHttpsCertificates() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[1];
            TrustManager tm = new MyTrustManager();
            trustAllCerts[0] = tm;
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init((KeyManager[])null, trustAllCerts, (SecureRandom)null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (NoSuchAlgorithmException var3) {
            var3.printStackTrace();
            logger.debug(var3);
        } catch (KeyManagementException var4) {
            var4.printStackTrace();
            logger.debug(var4);
        } catch (Exception var5) {
            var5.printStackTrace();
            logger.debug(var5);
        }
    }
}
